﻿using EFCore.BulkExtensions;
using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore;
using Signalrs.context;
using Signalrs.Model;

namespace Signalrs.HubModel
{
    public class ImportExecutor
    {
        private readonly IServiceProvider _serviceProvider;

        public IHubContext<ChatRoomHub> hubContext { get; set; }

        public ImportExecutor(IServiceProvider dbContext, IHubContext<ChatRoomHub> hubContext)
        {
            _serviceProvider = dbContext;
            this.hubContext = hubContext;
        }

        public async Task ExcuteAsync(string userId, string filename)
        {
            var savePath = Path.Combine("Uploads", filename);
            string[] lines = File.ReadAllLines(savePath);
            int totalCount = lines.Length - 1; //总行数，跳过表头
            using var scope = _serviceProvider.CreateScope();
            var _dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
            List<T_WordItems> t_WordItems1 = new List<T_WordItems>();
            //读取 遍历数据
            int count = 0;
            foreach (string line in lines)
            {
                string[] strs = line.Split(',');
                T_WordItems t_WordItems = new T_WordItems();
                t_WordItems.Word = strs[0] ?? "";
                t_WordItems.Phonetic = strs[1] ?? "";
                t_WordItems.Definition = strs[2] ?? "";
                t_WordItems.Translation = strs[3] ?? "";
                t_WordItems1.Add(t_WordItems);
                count++;
                //每1000条插入一次
                if (t_WordItems1.Count() == 1000)
                {
                    try
                    {
                        await _dbContext.BulkInsertAsync<T_WordItems>(t_WordItems1);  //批量插入
                                                                         //通知进度
                        hubContext.Clients.User(userId).SendAsync("ReceiveProgress", count, totalCount).Wait();
                        t_WordItems1 = new List<T_WordItems>();
                    }
                    catch (Exception ex)
                    {

                    }
             
                }

            }
            if (t_WordItems1.Count() > 0)
            {
                await _dbContext.BulkInsertAsync(t_WordItems1);  //批量插入
                                                                 //t_WordItems1 = new List<T_WordItems>();
                                                                 //通知进度
                hubContext.Clients.User(userId).SendAsync("ReceiveProgress", count, totalCount).Wait();
            }
        }
    }
}
